/*
 * Copyright (C) 2011 CrystalRange
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.crystalrange.web;

import java.util.Set;
import org.crystalrange.BaseController;
import org.crystalrange.Message;
import org.crystalrange.model.Authority;
import org.crystalrange.model.Role;
import org.crystalrange.model.User;
import org.crystalrange.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Window;

public class UserController extends BaseController {

    protected UserService userService;
    protected User user;
    protected Listbox listboxRole;
    protected Listbox listboxAuthority;

    public UserService getUserService() {
        return this.userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public void doAfterCompose(Component component) throws Exception {
        super.doAfterCompose(component);

        if (this.execution.getParameter("Id") != null) {
            this.user = this.userService.find(
                    Long.parseLong(this.execution.getParameter("Id")));
            this.labelTitle.setValue("Edit User");
        } else {
            this.user = this.userService.create(
                    SecurityContextHolder.getContext().getAuthentication().getName());
            this.labelTitle.setValue("Create User");
        }

        component.setAttribute("controller", this);
    }

    public void onClick$toolbarbuttonRoleAdd(Event event) throws Exception {
        this.roleAdd();
    }

    public void onClick$toolbarbuttonRoleRemove(Event event) throws Exception {
        this.roleRemove();
    }

    public void onClick$menuitemRoleAdd(Event event) throws Exception {
        this.roleAdd();
    }

    public void onClick$menuitemRoleRemove(Event event) throws Exception {
        this.roleRemove();
    }

    public void onClick$toolbarbuttonAuthorityAdd(Event event) throws Exception {
        this.authorityAdd();
    }

    public void onClick$toolbarbuttonAuthorityRemove(Event event) throws Exception {
        this.authorityRemove();
    }

    public void onClick$menuitemAuthorityAdd(Event event) throws Exception {
        this.authorityAdd();
    }

    public void onClick$menuitemAuthorityRemove(Event event) throws Exception {
        this.authorityRemove();
    }

    public void onClick$menuitemUserSave(Event event) throws Exception {
        this.userSave();
    }

    public void onClick$toolbarbuttonUserSave(Event event) throws Exception {
        this.userSave();
    }

    public void roleAdd() throws Exception {
        Window window = (Window) this.execution.createComponents("~./zul/html/roleSelect.zul", null, null);
        window.setParent(self);
        window.doModal();

        if (this.execution.getAttribute("result") == "ok") {
            Role selectedRole = (Role) this.execution.getAttribute("selectedRole");
            this.user.getRoles().add(selectedRole);
        }

        this.binder.loadComponent(this.listboxRole);
    }

    private void roleRemove() throws Exception {
        Set<Listitem> selectedItems = this.listboxRole.getSelectedItems();

        for (Listitem selectedItem : selectedItems) {
            Role selectedRole = (Role) selectedItem.getValue();
            this.user.getRoles().remove(selectedRole);
        }

        this.binder.loadComponent(this.listboxRole);
    }

    public void authorityAdd() throws Exception {
        Window window = (Window) this.execution.createComponents("~./zul/html/authoritySelect.zul", null, null);
        window.setParent(self);
        window.doModal();

        if (this.execution.getAttribute("result") == "ok") {
            Authority selectedAuthority = (Authority) this.execution.getAttribute("selectedAuthority");
            this.user.getAuthorities().add(selectedAuthority);
        }

        this.binder.loadComponent(this.listboxAuthority);
    }

    private void authorityRemove() throws Exception {
        Set<Listitem> selectedItems = this.listboxAuthority.getSelectedItems();

        for (Listitem selectedItem : selectedItems) {
            Authority selectedAuthority = (Authority) selectedItem.getValue();
            this.user.getAuthorities().remove(selectedAuthority);
        }

        this.binder.loadComponent(this.listboxAuthority);
    }

    private void userSave() throws Exception {
        this.userService.save(this.user,
                SecurityContextHolder.getContext().getAuthentication().getName());
        this.sessionScope.put("CRYSTALRANGE_MESSAGE", new Message("Saved successfully!"));
        Clients.evalJavaScript("window.history.back();");
    }
}
